package main

import (
	"encoding/json"
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"time"
)

func main() {
	opt := mqtt.NewClientOptions()
	//address := fmt.Sprintf("%s://%s:%s", "mqtt", "localhost", "1883")
	address := fmt.Sprintf("%s://%s:%s", "tcp", "localhost", "1883")
	opt.AddBroker(address)
	opt.SetClientID("mqttx_123456")

	// 遗嘱信息 只有发生意外情况才会发送
	lastWillData := newData("finished!")
	data, _ := json.Marshal(lastWillData)
	opt.SetBinaryWill("local/info", data, 0, false)
	opt.SetKeepAlive(time.Second * 1)
	/*
		tls
			opt.SetUsername("username")
			opt.SetPassword("pass")
	*/
	client := mqtt.NewClient(opt)
	token := client.Connect()
	if token.Wait(); token.Error() != nil {
		fmt.Println("connect to local mqtt broker failed, err=", token.Error())
		return
	}
	for i := 0; i < 10; i++ {
		message := newData(fmt.Sprintf("Hello, %d", i+10))
		b, err := json.Marshal(message)
		if err != nil {
			fmt.Println("marshal failed,err=", err)
			continue
		}
		t := client.Publish("local/info", 2, false, b)
		go func() {
			_ = t.Wait()
			if t.Error() != nil {
				fmt.Println(t.Error())
			}
		}()
	}

	// 正常结束不会发送遗嘱信息
	client.Disconnect(2500)
}

type Data struct {
	Code int    `json:"code"`
	Msg  string `json:"msg"`
}

func newData(msg string) Data {
	return Data{
		Code: 200,
		Msg:  msg,
	}
}
